import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class Task {

    //模拟缓冲区
    private static LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<>();
    //耗时0.3秒
    private static Integer DriverTime = 300;
    private static Integer workerTime = 500;

    //数量  使用原子类保证了并发情况下面的一致性
    private static AtomicInteger value = new AtomicInteger(0);
    //最大数量
    private static Integer maxValue = 10;
    private static Integer count = 5;


    private static boolean isWorked = false;

    public static void main(String[] args) {
        Thread driver1 = new Thread(new Driver());
        Thread driver2 = new Thread(new Driver());
        Thread worker = new Thread(new worker());
        worker.start();
        driver1.start();
        driver2.start();
    }

    static class Driver implements Runnable {

        @Override
        public void run() {
            try {
                //耗时0.3s
                Thread.sleep(DriverTime);
                //五次
                for (int i = 0; i < count; i++) {
                    //物品个数++
                    int currentValue = value.incrementAndGet();
                    //放入到缓冲区中
                    queue.put(currentValue);
                    System.out.println("货车存入1件,当前库存:" + currentValue + "/" + maxValue);
                }
                isWorked = true;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class worker implements Runnable {

        @Override
        public void run() {
            //去除包裹
            //结束的逻辑
            while (true) {
                if (queue.isEmpty() && isWorked == true) {
                    //结束工作
                    break;
                }
                try {
                    Thread.sleep(workerTime);
                    //从缓冲区中取出进行消费
                    Integer getValue = queue.take();
                    System.out.println("当前库存:" + getValue + "/" + maxValue);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
